<script setup>
	import { ref } from 'vue';
	import { verifyCode,loginByMobileApi } from '@/services/user';
	import { useUserStore } from '../../../stores/user';
	
	const showCountdown = ref(false);
	const user = useUserStore()
	
	const fromData = ref({
		mobile: '18959118574',
		code: '',
		password: '123456yy'
		
	})
	
	// 获取组件实例
	const formRef = ref()
	const isAgree = ref(false);
	
	async function onTextButtonClick(get=false) {
		//跳转页面
		// uni[user.openType]({
		// 	url: user.recirectURL
		// })
		
		if (!isAgree.value) return uni.utils.toast("请勾选协议");
		showCountdown.value = showCountdown.value ? false : true;
		if(get) {
			const {code, data, message} = await verifyCode({
				mobile: fromData.value.mobile,
				type: 'register',
			})
			fromData.value.code = data.code;
			if(code !== 200) return uni.utils.toast(message);
		}
		
	}
	
	const formRules = {
	  mobile: {
	    rules: [
	      { required: true, errorMessage: '请填写手机号码' },
	      { pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
	    ],
	  },
	  code: {
	    rules: [
	      { required: true, errorMessage: '请输入验证码' },
	      { pattern: '^\\d{6}$', errorMessage: '验证码格式不正确' },
	    ],
	  },
	}
	
	//  勾选协议
	function onAgreeClick() {
	  isAgree.value = !isAgree.value;
	}
	
	async function onLogin() {
		try {
			const result = await formRef.value.validate()
			const res = await loginByMobileApi({mobile:fromData.value.mobile,
			code:fromData.value.code,password:fromData.value.password})
			console.log(res);
		} catch (e) {
			console.log(e);
		}
	}
	
</script>

<template>
	<uni-forms class="login-form" :model="fromData" :rules="formRules" ref="formRef">
	  <uni-forms-item name="mobile">
	    <uni-easyinput
		   v-model="fromData.mobile"
	      :input-border="false"
	      :clearable="false"
	      placeholder="请输入手机号"
	      placeholder-style="color: #C3C3C5"
	    />
	  </uni-forms-item>
	  <uni-forms-item name="code">
	    <uni-easyinput
	      :input-border="false"
	      :clearable="false"
	      placeholder="请输入验证码"
	      placeholder-style="color: #C3C3C5"
		  v-model="fromData.code"
	    />
		<view class="text-button" v-if='showCountdown'>
			<uni-countdown 
			 :show-day="false"
			 :show-hour="false" 
			 :showMinute="false"
			 :second="5"
			 color='#16c2a3'
			 @timeup="onTextButtonClick"
			 >
			 </uni-countdown>秒后重新获取
		</view>
	    <text v-else @click="onTextButtonClick(true)" class="text-button">获取验证码</text>
	  </uni-forms-item>
	
	  <view class="agreement">
	    <radio :checked="isAgree" @click="onAgreeClick" color="#16C2A3" />
	    我已同意
	    <text class="link">用户协议</text>
	    及
	    <text class="link">隐私协议</text>
	  </view>
	
	  <button class="uni-button" @click="onLogin">登录</button>
	</uni-forms>
</template>


<script>
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>

<style lang="scss">
@import './styles.scss';
</style>
